package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-07-11
 * Time: 8:49
 */
public class TCPEchoServer {
    //serverSocket —— 外场拉客的小哥
    //clientSocket —— 内场服务的小姐姐
    // serverSocket 只有一个，clientSocket 会给每个客户端分配一个
    private ServerSocket serverSocket = null;

    public TCPEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("服务器启动！");
        //死循环  —— 服务器一直在用 无时无刻不在接收客户端的请求
        while(true) {
            Socket clientSocket = serverSocket.accept();
            //如果直接调用该方法会影响这个循环的二次执行，导致accept不及时了
            //创建新的线程,用新的线程来调用 processConnection
            //每次来一个新的客户端都搞一个新的线程即可
//            Thread t = new Thread(() ->{
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
//            t.start();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    //通过这个方法来处理一个连接
    //读取请求
    //根据请求计算响应
    //把响应返回给客户端
    private void processConnection(Socket clientSocket) throws IOException {
        //长连接为例子，处理多个请求
        //try这种写法，括号中允许写多个流对象，使用;分割
        System.out.printf("[%s:%d] 客户端上线！\n",clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner sc = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true) {
                //1.读取请求
                if(!sc.hasNext()) {
                    //读取到流的结尾了(对端关闭)
                    System.out.printf("[%s:%d] 客户端下线\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                //直接使用scanner读取一段字符串
                String request = sc.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.把响应返回给客户端 响应记得换行
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req:%s,resp:%s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);
            }
        }catch (IOException e) {
            e.printStackTrace();
            //clientSocket 只是给一个连接提供服务的,这个东西还是要能够进行关闭
        } finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer tcpEchoServer = new TCPEchoServer(9090);
        tcpEchoServer.start();
    }
}
